import 'package:erp_widget/src/theme/index.dart';
import 'package:flutter/widgets.dart';

class DxFutureBuilder<T> extends StatefulWidget {
  /// Future to resolve.
  final Future<T> future;

  /// Whether or not the future result should be stored.
  final bool rememberResult;

  /// Widget to display when connected to an asynchronous computation and awaiting interaction.
  final Widget Function()? onLoading;

  /// Function to call when the asynchronous computation is done.
  final Widget Function(T? snapshotData) onDone;

  /// Function to call when the asynchronous computation is done with error.
  /// If no function is passed, whenNotDone() will be used instead
  final Widget Function(Object? error)? onError;

  /// The data that will be used until a non-null [future] has completed.
  ///
  /// See [FutureBuilder] for more info
  final T? initialData;

  const DxFutureBuilder({
    Key? key,
    this.rememberResult = true,
    required this.future,
    required this.onDone,
    this.onError,
    this.onLoading,
    this.initialData,
  }) : super(key: key);

  @override
  State<DxFutureBuilder<T>> createState() => _DxFutureBuilderState<T>();
}

class _DxFutureBuilderState<T> extends State<DxFutureBuilder<T>> {
  late Future<T> _cachedFuture;

  @override
  void initState() {
    super.initState();
    _cachedFuture = widget.future;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<T>(
      future: widget.rememberResult ? _cachedFuture : widget.future,
      initialData: widget.initialData,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return widget.onError?.call(snapshot.error) ?? _buildDefault(snapshot.error.toString());
          }
          return widget.onDone.call(snapshot.data);
        }
        return widget.onLoading?.call() ?? _buildDefault('加载中……');
      },
    );
  }

  Widget _buildDefault(String text) {
    return Center(child: Text(text, style: DxStyle.$999999$12));
  }
}
